<template>
    <div class="search">
      <el-input clearable @clear="load" style="width: 260px; margin-right: 5px" v-model="data.name" placeholder="请输入名称查询" :prefix-icon="Search"></el-input>
      <el-button type="primary" style="margin-left: 15px;" @click="load">查 询</el-button>
    </div>
    <div class="tool">
      <el-button type="success" @click="handleAdd" style="margin: 15px;" >新 增</el-button>
      <el-button type="danger" @click="deleteBatch" style="margin: 15px;" >删 除</el-button>
    </div>
    <el-dialog title="管理员信息" v-model="data.formVisible" width="500" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px" style="padding: 20px 30px 10px 0">
        <el-form-item prop="avatar" label="头像">
          <el-upload
            action="http://localhost:8080/files/upload"
            :headers="{ token: data.user.token }"
            :on-success="handleSearch"
            list-type="picture"
          >
            <el-button type="primary">上传头像</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item prop="username" label="账号">
          <el-input v-model="data.form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="name" label="名称">
          <el-input v-model="data.form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="phone" label="电话">
          <el-input v-model="data.form.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="data.form.email" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>

    <div class="content" >
      <el-table :data="data.tableData" @selection-change="handleSelectionChange" style="width: 100%" :header-cell-style="{ color: '#333', backgroundColor: '#eaf4ff' }">
        <!-- <el-table-column prop="id" label="序号" width="100" />
        <el-table-column prop="nameId" label="编号" width="200" />
        <el-table-column prop="name" label="名字" />
        <el-table-column prop="type" label="类型"  />
        <el-table-column prop="num" label="剩余量" />
        <el-table-column prop="inNum" label="今日入库数"  />
        <el-table-column prop="outNum" label="今日出库数"  />
        <el-table-column prop="time" label="更新时间"/> -->

        <el-table-column type="selection" width="55" />
        <el-table-column label="头像">
          <template #default="scope">
            <el-image v-if="scope.row.avatar" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]" :preview-teleported="true"
                      style="width: 40px; height: 40px; border-radius: 50%; display: block" />
          </template>
        </el-table-column>
        <el-table-column prop="username" label="账号" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column  label="操作" >
          <template #default="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
        
      </el-table>
    </div>
    <div class="card">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-size="data.pageSize"
          layout="total,sizes, prev, pager, next"
          :total="data.total"
          :page-sizes="[5, 10, 20, 40, 80]"
          @current-change="load"
          @size-change="load"
      />
    </div>
</template>

<script setup>
import { reactive,ref } from "vue";
import {Search} from "@element-plus/icons-vue";
import request from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
const formRef = ref()
const data = reactive({
  user: JSON.parse(localStorage.getItem("code_user")||"{}"), 
  name: null,
  pageNum: 1,
  pageSize: 5,
  total: 0,
  formVisible: false,
  tableData: [],
  form:{
    username:'',
    name:'',
    phone:'',
    email:''
  },
  rules:{
    username: [
      { required: true, message: '请输入账号', trigger: 'blur' },
      // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
    name: [
      { required: true, message: '请输入名称', trigger: 'blur' },
      // { min: 3, max:5, message: '长度在 3 到 5 个字符',}
    ],
    phone: [
      { required: true, message: '请输入电话', trigger: 'blur' },
      // { min: 3, max:5, message: '长度在 3 到 5 个字符',}
    ],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      // { min: 3, max:5, message: '长度在 3 到 5 个字符',}
    ]
  },
  rows:[]
})

const load=()=>{
  request.get('/user/selectPage',{
      params:{
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      name:data.name
      }
    }
  ).then(res=>{
    if(res.code=='200'){
      data.tableData=res.data.list
      data.total=res.data.total
    }else{
      ElMessage.error(res.msg)
    }
    
  })
}
load()
const handleAdd=()=>{
  data.formVisible=true
  data.form={}
}
const add=()=>{
  formRef.value.validate((valid) => {
    if (valid) {  
     // 验证通过的情况下
     request.post('/user/add',data.form).then(res=>{
    if(res.code=='200'){
      ElMessage.success("新增成功")
      data.formVisible=false
      load()
    }else{
      ElMessage.error("新增失败")
      data.formVisible=false
    }
  })
  }
}) 
}

const save=()=>{
  data.form.id? update():add()
}

const del=(id)=>{
  ElMessageBox.confirm("是否删除该管理员？",'删除确认',{type:'warning'}).then(res=>{
    request.delete('/user/delete/'+id).then(res=>{
      if(res.code=='200'){
        ElMessage.success("删除成功")
        load()
      }else{
        ElMessage.error("删除失败")
      }
    })
  }).catch(res=>{
    console.log('res',res)
  })
  // request.get('/user/delete',{
  //   params:{
  //     id:id
  //   }
  // }).then(res=>{
  //   if(res.code=='200'){
  //     ElMessage.success("删除成功")
  //     load()
  //   }else{
  //     ElMessage.error("删除失败")
  //   }
  // })
}

const handleEdit=(row)=>{
  console.log('row',row)
  data.form=JSON.parse(JSON.stringify(row)) // 要使用深拷贝，浅拷贝不行，还没保存就会跟着改变，深拷贝就是两个不相干的对象
  data.formVisible=true
}
const update=()=>{
  formRef.value.validate((valid) => {
    if (valid) {
      request.post('/user/update',data.form).then(res=>{
        if(res.code=='200'){
          ElMessage.success("修改成功")
          data.formVisible=false
          load()
        }else{
          ElMessage.error("修改失败")
          data.formVisible=false
        }
      })
    }
})
}

const handleSelectionChange=(rows)=>{
  // rows是实际选择的数组
  console.log('rows',rows)
  data.rows=rows
}

const deleteBatch = () => {
  if (data.rows.length === 0) {
    ElMessage.warning('请选择数据')
    return
  }
  ElMessageBox.confirm('删除后无法恢复，您确认删除吗？', '删除确认', { type: 'warning' }).then(res => {
    request.delete('/user/deleteBatch', { data: data.rows }).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {})
}

const handleSearch=(res)=>{
  data.form.avatar=res.data
}
</script>
<style scoped lang="css">
.search{
  margin-bottom: 25px
}

.content{
  margin-bottom: 25px
}
</style>